package servlets;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import managers.XsltManager;

import org.w3c.dom.Document;

import com.oreilly.servlet.MultipartRequest;

import dataBase.magaers.CodeDBMngr;
import dataBase.magaers.UserDBMngr;
import dataBase.magaers.XsltDBManager;

/**
 * Servlet implementation class XsltServlet
 */
public class XsltServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public XsltServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		MultipartRequest multi = new MultipartRequest(request, "." ,5 * 1024 * 1024);

		File ff = multi.getFile("upload");
		Enumeration files = multi.getFileNames();
		while (files.hasMoreElements()) {
			String name = (String) files.nextElement();
			String uploadedXsl =  getContents(multi.getFile(name));
			XsltDBManager.getInstance().insertXsl(uploadedXsl);
		}
		response.setContentType("text/html");
		ServletOutputStream out = response.getOutputStream();
		out.print("<html><head><title>upload</title></head><body><h3>Your xsl file uploaded successfully</h3></body></html>");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String title = request.getParameter("title");
		String xslId = request.getParameter("xslId");
		if (xslId == null)
			xslId = "1";
		CodeDBMngr cdbm = CodeDBMngr.getInstance();
		if (cdbm == null) {
			response.sendError(500);
			return;
		}
		String uid = (String)request.getSession().getAttribute("email");
		Document dom;
		if (uid == null){ // the user is not logged in
			dom = cdbm.searchByTitle(title, "" , false);			
		}
		else {
			dom = cdbm.searchByTitle(title, uid , UserDBMngr.getInstance().isAdmin(uid));			
		}
		if (dom == null) {
			response.sendError(500);
			return;
		}
		XsltManager.translate(dom, xslId, response.getOutputStream());

	}
	 static public String getContents(File aFile) {
		    //...checks on aFile are elided
		    StringBuilder contents = new StringBuilder();
		    
		    try {
		      //use buffering, reading one line at a time
		      //FileReader always assumes default encoding is OK!
		      BufferedReader input =  new BufferedReader(new FileReader(aFile));
		      try {
		        String line = null; //not declared within while loop
		        /*
		        * readLine is a bit quirky :
		        * it returns the content of a line MINUS the newline.
		        * it returns null only for the END of the stream.
		        * it returns an empty String if two newlines appear in a row.
		        */
		        while (( line = input.readLine()) != null){
		          contents.append(line);
		          contents.append(System.getProperty("line.separator"));
		        }
		      }
		      finally {
		        input.close();
		      }
		    }
		    catch (IOException ex){
		      ex.printStackTrace();
		    }
		    
		    return contents.toString();
		  }

}
